"""
配置文件处理模块，用于读取config.ini并提供配置信息
"""
import configparser
import os
from pathlib import Path
from typing import Dict, List, Optional, Union, Any
import ast


class Settings:
    """应用配置设置类"""

    def __init__(self):
        # 获取项目根目录
        self.BASE_DIR = Path(__file__).parent.parent.parent.absolute()

        # 读取配置文件
        config = configparser.ConfigParser()
        config_path = os.path.join(self.BASE_DIR, "config.ini")
        config.read(config_path, encoding="utf-8")

        # 应用配置
        self.APP_NAME = config.get("APP", "APP_NAME")
        self.DEBUG = config.getboolean("APP", "DEBUG")
        self.SECRET_KEY = config.get("APP", "SECRET_KEY")
        self.ALLOWED_HOSTS = [host.strip() for host in config.get("APP", "ALLOWED_HOSTS").split(",")]

        # 服务器配置
        self.HOST = config.get("SERVER", "HOST")
        self.PORT = config.getint("SERVER", "PORT")
        self.RELOAD = config.getboolean("SERVER", "RELOAD")
        self.WORKERS = config.getint("SERVER", "WORKERS")
        self.LOG_LEVEL = config.get("SERVER", "LOG_LEVEL").lower()
        self.AUTH_REQUIRED = config.getboolean("SERVER", "AUTH_REQUIRED")

        # 数据库配置
        self.DATABASE_URL = config.get("DATABASE", "DATABASE_URL")
        self.MIGRATE = config.getboolean("DATABASE", "MIGRATE")

        # JWT配置
        self.JWT_SECRET_KEY = config.get("JWT", "SECRET_KEY")
        self.JWT_ALGORITHM = config.get("JWT", "ALGORITHM")
        self.JWT_ACCESS_TOKEN_EXPIRE_MINUTES = config.getint("JWT", "ACCESS_TOKEN_EXPIRE_MINUTES")
        self.JWT_REFRESH_TOKEN_EXPIRE_DAYS = config.getint("JWT", "REFRESH_TOKEN_EXPIRE_DAYS")
        self.EXCLUDE_ROUTES = self._parse_list_or_str(config.get("JWT", "EXCLUDE_ROUTES"))
        self.LOGIN_ROUTE = config.get("JWT", "LOGIN_ROUTE")

        # 日志配置
        self.LOG_LEVEL = config.get("LOG", "LEVEL")
        self.LOG_FORMAT = config.get("LOG", "FORMAT")
        self.LOG_FILE_ENABLED = config.getboolean("LOG", "FILE_ENABLED")
        self.LOG_FILE_PATH = config.get("LOG", "FILE_PATH")
        self.LOG_MAX_SIZE = config.getint("LOG", "MAX_SIZE")
        self.LOG_BACKUP_COUNT = config.getint("LOG", "BACKUP_COUNT")
        self.LOG_CONSOLE_OUTPUT = config.getboolean("LOG", "CONSOLE_OUTPUT")

        # CORS配置
        self.CORS_ORIGINS = self._parse_list_or_str(config.get("CORS", "ORIGINS"))
        self.CORS_METHODS = self._parse_list_or_str(config.get("CORS", "METHODS"))
        self.CORS_HEADERS = self._parse_list_or_str(config.get("CORS", "HEADERS"))
        self.CORS_ALLOW_CREDENTIALS = config.getboolean("CORS", "ALLOW_CREDENTIALS")

    def _parse_list_or_str(self, value: str) -> List[str]:
        """解析字符串或列表配置"""
        try:
            import json
            return json.loads(value)
        except json.JSONDecodeError:
            return [item.strip() for item in value.split(",")]


# 创建全局设置实例
settings = Settings()
